package com.hjh.testdemo

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import androidx.activity.viewModels
import com.hjh.core.activity.BaseActivity
import com.hjh.testdemo.databinding.ActivityMainBinding
import com.hjh.usb.accessory.AOAService
import com.hjh.usb.accessory.UsbConnectionViewModel
import com.hjh.usb.accessory.communication.ConnectionState

@Suppress("unused")
class MainActivity : BaseActivity<ActivityMainBinding>() {

    init {
        initResId(mainId = R.id.main, navHostId = R.id.nav_host)
    }

    // Usb AOA
    private val viewModel: UsbConnectionViewModel by viewModels()
    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val binder = service as AOAService.LocalBinder
            viewModel.setService(binder.getService())
        }
        override fun onServiceDisconnected(name: ComponentName?) {
            viewModel.releaseService()
            viewModel.updateConnectionState(ConnectionState.Disconnected)
        }
    }

    override fun initView() {
        requestPermission(storage = true, writeStorage = true, readStorage = true)
        // Usb AOA 启动前台服务，进行AOA通信
        Intent(this, AOAService::class.java).also { intent ->
            bindService(intent, serviceConnection, BIND_AUTO_CREATE)
        }
    }

    override fun release() {
        // Usb AOA 释放资源
        if (viewModel.serviceBound) {
            unbindService(serviceConnection)
            viewModel.serviceBound = false
        }
    }
}